package framework
import (
	"fmt"
	"strings"
	"errors"
	"signaling/src/framework/xrpc"
	"strconv"
	"time"
	"bytes"
	"encoding/json"

)

var xrpcClients map[string]*xrpc.Client = make(map[string]*xrpc.Client)

func loadXrpc() error {


	sections := configFile.GetSectionList()
	// fmt.Println(sections)
	for _,section := range sections {

		if !strings.HasPrefix(section,"xrpc."){
			continue
		}
		// fmt.Println(section)
		mSection ,err := configFile.GetSection(section)
		if err != nil {
			return err
		}
		//server
		values, ok := mSection["server"]
		if !ok {
			return errors.New("no server in config file")
		}
		arrSever := strings.Split(values,",")

		//去掉空格
		for i,server := range arrSever {
			arrSever[i] = strings.TrimSpace(server)
		}
		fmt.Println(arrSever)
		client := xrpc.NewClient(arrSever)
		//connectTimeout

		if values,ok := mSection["connectTimeout"];ok {
			if connectTimeout,err := strconv.Atoi(values);err == nil {
				client.ConnectTimeout = time.Duration(connectTimeout)*time.Millisecond
			}
		}
		if values,ok := mSection["readTimeout"];ok {
			if readTimeout,err := strconv.Atoi(values);err == nil {
				client.ReadTimeout = time.Duration(readTimeout)*time.Millisecond
			}
		}
		if values,ok := mSection["writeTimeout"];ok {
			if writeTimeout,err := strconv.Atoi(values);err == nil {
				client.WriteTimeout = time.Duration(writeTimeout)*time.Millisecond
			}
		}

		xrpcClients[section] = client
		fmt.Println(client)
	}
	return nil
}
func Call(serviceName string ,request interface{},response interface{},
	logId uint32) error {
		fmt.Println("Call " + serviceName)

		//

		client ,ok := xrpcClients["xrpc."+ serviceName]
		if !ok {
			return fmt.Errorf("[%s] service not found",serviceName)
		}


		content, err := json.Marshal(request)
		if err != nil {
			return err
		}
		req := xrpc.NewRequest(bytes.NewReader(content),logId)
		//client ->Do()
		resp ,err := client.Do(req)
		if err != nil {
			return err
		}
	

		//将response 反序列化json 结构
		err = json.Unmarshal(resp.Body, response)
		if err != nil {

			return err
		}
		fmt.Println(resp)
		return nil
}
